<template>
  <div class="user-management">
    <h2>用户管理</h2>
    <div class="toolbar">
      <el-button type="primary" @click="handleAddUser">新增用户</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户..."
        style="width: 300px; margin-left: 20px;"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    
    <vxe-table 
      :data="filteredUsers" 
      border 
      show-overflow 
      highlight-hover-row
      style="width: 100%; margin-top: 20px;"
      :auto-resize="true"
      :resizable="true"
    >
      <vxe-column field="id" title="用户ID"></vxe-column>
      <vxe-column field="username" title="用户名"></vxe-column>
      <vxe-column field="email" title="邮箱"></vxe-column>
      <vxe-column field="role" title="角色">
        <template #default="{ row }">
          <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
            {{ row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column field="status" title="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'warning'">
            {{ row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column field="createTime" title="创建时间"></vxe-column>
      <vxe-column title="操作">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="row.status === 'active' ? 'warning' : 'success'"
            @click="handleChangeStatus(row)"
          >
            {{ row.status === 'active' ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    
    <div class="pagination">
      <vxe-pager
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="totalUsers"
        :layouts="['Total', 'PrevPage', 'Number', 'NextPage', 'Sizes', 'Jump']"
        :page-sizes="[10, 20, 50]"
        @page-change="handlePageChange"
      />
    </div>
    
    <!-- 用户编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="currentUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="currentUser.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="currentUser.status"
            :active-value="'active'"
            :inactive-value="'inactive'"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

// 模拟用户数据
const mockUsers = [
  { id: 1, username: 'admin', email: 'admin@example.com', role: 'admin', status: 'active', createTime: '2023-01-01 12:00:00' },
  { id: 2, username: 'doctor1', email: 'doctor1@example.com', role: 'user', status: 'active', createTime: '2023-02-01 14:30:00' },
  { id: 3, username: 'doctor2', email: 'doctor2@example.com', role: 'user', status: 'active', createTime: '2023-03-01 10:15:00' },
  { id: 4, username: 'nurse1', email: 'nurse1@example.com', role: 'user', status: 'inactive', createTime: '2023-04-01 09:45:00' },
  { id: 5, username: 'tech1', email: 'tech1@example.com', role: 'user', status: 'active', createTime: '2023-05-01 16:20:00' }
]

const users = ref(mockUsers)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(mockUsers.length)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentUser = ref({})

// 计算过滤后的用户数据
const filteredUsers = computed(() => {
  let result = users.value
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(keyword) || 
      user.email.toLowerCase().includes(keyword)
    )
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 处理分页大小变化
const handlePageChange = ({ currentPage: newPage, pageSize: newPageSize }) => {
  currentPage.value = newPage
  pageSize.value = newPageSize
}

// 处理新增用户
const handleAddUser = () => {
  dialogTitle.value = '新增用户'
  currentUser.value = {
    id: Date.now(), // 简单生成唯一ID
    username: '',
    email: '',
    role: 'user',
    status: 'active',
    createTime: new Date().toLocaleString()
  }
  dialogVisible.value = true
}

// 处理编辑用户
const handleEdit = (user) => {
  dialogTitle.value = '编辑用户'
  currentUser.value = { ...user }
  dialogVisible.value = true
}

// 处理更改用户状态
const handleChangeStatus = (user) => {
  const newStatus = user.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${action}用户 ${user.username} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    users.value = users.value.map(u => 
      u.id === user.id ? { ...u, status: newStatus } : u
    )
    ElMessage.success(`${action}用户成功`)
  }).catch(() => {
    // 取消操作
  })
}

// 处理删除用户
const handleDelete = (user) => {
  ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？此操作不可恢复！`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
    }).then(() => {
    users.value = users.value.filter(u => u.id !== user.id)
    ElMessage.success('删除用户成功')
  }).catch(() => {
    // 取消操作
  })
}

// 保存用户
const saveUser = () => {
  if (!currentUser.value.username || !currentUser.value.email) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  if (dialogTitle.value === '新增用户') {
    // 新增用户
    users.value.push({ ...currentUser.value })
    ElMessage.success('新增用户成功')
  } else {
    // 编辑用户
    users.value = users.value.map(user => 
      user.id === currentUser.value.id ? { ...currentUser.value } : user
    )
    ElMessage.success('编辑用户成功')
  }
  
  dialogVisible.value = false
}

// 组件挂载时获取用户数据
onMounted(() => {
  // 这里可以调用API获取真实的用户数据
  console.log('获取用户数据...')
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.toolbar .el-button {
  margin-bottom: 10px;
}

.toolbar .el-input {
  margin-bottom: 10px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar .el-input {
    margin-left: 0;
    margin-top: 10px;
  }
}

/* 表格自适应 */
.vxe-table {
  width: 100% !important;
  table-layout: fixed;
}

.vxe-table .vxe-body--column {
  text-align: center;
}

.vxe-table .vxe-cell {
  padding: 8px 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 操作按钮响应式 */
.vxe-table .vxe-cell .el-button {
  margin: 2px;
  padding: 5px 10px;
}

/* 分页响应式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 小屏幕设备上的分页调整 */
@media (max-width: 768px) {
  .pagination {
    justify-content: center;
  }
  
  .vxe-pager .vxe-pager--wrapper {
    flex-wrap: wrap;
  }
  
  .vxe-pager .vxe-pager--sizes {
    margin-bottom: 10px;
  }
  
  .vxe-pager .vxe-pager--jump {
    margin-top: 10px;
  }
}

/* 对话框响应式 */
@media (max-width: 768px) {
  .el-dialog {
    width: 90% !important;
  }
}
</style>